package com.example.filter;

import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.HttpExchange;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

public class SessionFilter extends Filter {

    private static final Map<String, String> sessions = new HashMap<>();
    @Override
    public void doFilter(HttpExchange httpExchange, Chain chain) throws IOException {
        // 从请求头中获取Cookie
        String sessionId = getSessionIdFromCookie(httpExchange.getRequestHeaders().getFirst("Cookie"));
        // 检查会话是否存在
        if (sessionId != null && sessions.containsKey(sessionId)) {
            // 会话存在
            String response = "Hello, return user!";
            httpExchange.sendResponseHeaders(200, response.length());
            OutputStream os = httpExchange.getResponseBody();
            os.write(response.getBytes());
            os.close();
        } else {
            // 会话不存在，进行会话创建
            sessionId = createNewSession();
            String response = "Hello, new user!";
            httpExchange.getResponseHeaders().add("Set-Cookie", "sessionId=" + sessionId);
            httpExchange.sendResponseHeaders(200, response.length());
            OutputStream os = httpExchange.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
    }

    @Override
    public String description() {
        return null;
    }

    private static String getSessionIdFromCookie(String cookieHeader) {
        if (cookieHeader != null) {
            String[] cookies = cookieHeader.split(";");
            for (String cookie : cookies) {
                if (cookie.trim().startsWith("sessionId=")) {
                    return cookie.trim().substring("sessionId=".length());
                }
            }
        }
        return null;
    }

    private static String createNewSession() {
        // 生成一个唯一的会话ID
        String sessionId = "session_" + System.currentTimeMillis();
        // 保存会话信息
        sessions.put(sessionId, "data");
        return sessionId;
    }
}
